/* eslint-disable */

import Simditor from "tar-simditor";
class UploadFile extends Simditor.Button {
  constructor(...args) {
    super(...args);
    this.createElement();
  }
  createElement() {
    this.input = document.createElement("input");
    this.input.type = "file";
    this.input.style =
      "position:absolute;top:0;right:0;height:100%;width:100%;opacity:0;filter:alpha(opacity=0);cursor:pointer;";
    this.el.appendChild(this.input);

    this.input.addEventListener("click", function (e) {
      return e.stopPropagation();
    });
    this.input.addEventListener("mousedown", function (e) {
      return e.stopPropagation();
    });
    this.input.addEventListener("change", this.upload);
  }
  upload() {
    var formData = new FormData();
    formData.append("file", this.files[0]);
    fetch("/api/admin/upload_file", {
      method: "POST",
      body: formData,
    })
      .then((res) => res.json())
      .then((res) => {
        if (!res.success) {
          alert("upload file failed");
        } else {
          let link =
            '<a target="_blank" className="simditor-attach-link" href="' +
            res.file_path +
            '">' +
            res.file_name +
            "</a>";
          this.editor.setValue(this.editor.getValue() + link);
        }
      })
      .catch(function (res) {
        alert("upload file failed");
      });
  }
  name = "uploadfile";
  icon = "upload";
  i18n = {
    "zh-CN": {
      uploadfile: "上传文件",
    },
    "en-US": {
      uploadfile: "upload file",
    },
  };
}

Simditor.Toolbar.addButton(new UploadFile(Simditor.Button));
